package com.kelp.codetoolkit.ui.form

import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.modules
import com.intellij.openapi.ui.ComboBox
import com.intellij.ui.JBColor
import com.kelp.codetoolkit.enums.RemoteInvocationFrameworkEnum
import com.kelp.codetoolkit.respository.CodeToolkitGlobalSettingRepository
import com.kelp.codetoolkit.utils.ProjectUtil
import java.awt.FlowLayout
import javax.swing.BorderFactory
import javax.swing.DefaultComboBoxModel
import javax.swing.JLabel
import javax.swing.JPanel
import javax.swing.border.LineBorder

/**
 * @author: liuyuebai
 * @date: 2025/1/25 20:01
 * @description:
 */
class ServerModuleSettingPanel(project: Project): JPanel() {

    private val serverModulePanel = JPanel(FlowLayout(FlowLayout.LEFT))
    private val serverModuleLabel = JLabel("Select Server Module: ")
    private val serverModule: DefaultComboBoxModel<String> = DefaultComboBoxModel()
    private val serverModuleBox: ComboBox<String> = ComboBox(serverModule)
    private var serverModuleName:String = ""

    init {
        serverModulePanel.isVisible = false
        val modules = project.modules
        val subModuleList = mutableListOf<Module>()
        for (module in modules) {
            if (module.name != project.name){
                subModuleList.add(module)
            }
        }
        val state = CodeToolkitGlobalSettingRepository.getInstance(project).state
        if (subModuleList.size>2 && RemoteInvocationFrameworkEnum.DUBBO.value == state.getRemoteInvocationFramework()){
            serverModulePanel.isVisible = true
            val moduleNames = modules.map { it.name }
            serverModule.addAll(moduleNames)
        }
        if (subModuleList.size == 2  && RemoteInvocationFrameworkEnum.DUBBO.value == state.getRemoteInvocationFramework()){
            val module = ProjectUtil.getServiceModule(project)
            if (module != null) {
                serverModuleName = module.name
            }
        }
        serverModuleBox.addActionListener{
            serverModuleName = serverModuleBox.selectedItem as String
        }
    }

    fun getServerModulePanel(): JPanel {
        serverModulePanel.add(serverModuleLabel)
        serverModulePanel.add(serverModuleBox)
        // 定义浅灰色
        val lightGray = JBColor.GRAY
        // 创建宽度为 1 像素、颜色为浅灰色的 LineBorder
        val lineBorder = LineBorder(lightGray, 1)
        // 创建带有标题的边框，使用上面创建的 LineBorder 作为边框
        val titledBorder = BorderFactory.createTitledBorder(lineBorder, "Project Sub Module")
        serverModulePanel.setBorder(titledBorder)
        return serverModulePanel
    }

    fun getServerModuleName(): String {
        return serverModuleName
    }
}